package com.lin.service.impl;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import com.lin.entity.Msg;
import com.lin.tool.ExcelReader;
import com.lin.tool.HBaseConnection;
import com.lin.tool.MoMoMsgGen;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.BufferedMutator;
import org.apache.hadoop.hbase.client.BufferedMutatorParams;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.RetriesExhaustedWithDetailsException;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.yetus.audience.InterfaceAudience;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * An example of using the {@link BufferedMutator} interface.
 */
@InterfaceAudience.Private
public class BufferedMutatorExample extends Configured implements Tool {

    private static final Logger LOG = LoggerFactory.getLogger(BufferedMutatorExample.class);

    private static final int POOL_SIZE = 10;
    private static final int TASK_COUNT = 100;
    private static final TableName TABLE = TableName.valueOf("MOMO_CHAT:MSG");
    private static final byte[] FAMILY = Bytes.toBytes("f");
    private Connection conn = HBaseConnection.connection;
    private Set<String> set = new HashSet<>();

    @Override
    public int run(String[] args) throws InterruptedException, ExecutionException, TimeoutException {

        /** a callback invoked when an asynchronous write fails. */
        final BufferedMutator.ExceptionListener listener = new BufferedMutator.ExceptionListener() {
            @Override
            public void onException(RetriesExhaustedWithDetailsException e, BufferedMutator mutator) {
                for (int i = 0; i < e.getNumExceptions(); i++) {
                    LOG.info("Failed to sent put " + e.getRow(i) + ".");
                }
            }
        };
        BufferedMutatorParams params = new BufferedMutatorParams(TABLE).listener(listener);

        //
        // step 1: create a single Connection and a BufferedMutator, shared by all worker threads.
        //
        try (final BufferedMutator mutator = conn.getBufferedMutator(params)) {

            /** worker pool that operates on BufferedTable instances */
            final ExecutorService workerPool = Executors.newFixedThreadPool(POOL_SIZE);
            List<Future<Void>> futures = new ArrayList<>(TASK_COUNT);

            Map<String, List<String>> resultMap = ExcelReader.readXlsx("E:\\ljl\\DataToHbase\\data\\测试数据集.xlsx", "陌陌数据");

            int i = 1;
            int max = 50001;

            while (i <= max){
                futures.add(workerPool.submit(new Callable<Void>() {
                    @Override
                    public Void call() throws Exception {
                        //
                        // step 2: each worker sends edits to the shared BufferedMutator instance. They all use
                        // the same backing buffer, call-back "listener", and RPC executor pool.
                        //
                        Msg oneMsg = MoMoMsgGen.getOneMsg(resultMap);
                        byte[] rowKey = MoMoMsgGen.getRowkey(oneMsg,set);
                        Put p = new Put(rowKey);
                        p.addColumn(Bytes.toBytes("f1"),Bytes.toBytes("msg_time"),Bytes.toBytes(oneMsg.getMsg_time()));
                        p.addColumn(Bytes.toBytes("f1"),Bytes.toBytes("sender_nickyname"),Bytes.toBytes(oneMsg.getSender_nickyname()));
                        p.addColumn(Bytes.toBytes("f1"),Bytes.toBytes("sender_account"),Bytes.toBytes(oneMsg.getSender_account()));
                        p.addColumn(Bytes.toBytes("f1"),Bytes.toBytes("sender_sex"),Bytes.toBytes(oneMsg.getSender_sex()));
                        p.addColumn(Bytes.toBytes("f1"),Bytes.toBytes("sender_ip"),Bytes.toBytes(oneMsg.getSender_ip()));
                        p.addColumn(Bytes.toBytes("f1"),Bytes.toBytes("sender_os"),Bytes.toBytes(oneMsg.getSender_os()));
                        p.addColumn(Bytes.toBytes("f1"),Bytes.toBytes("sender_phone_type"),Bytes.toBytes(oneMsg.getSender_phone_type()));
                        p.addColumn(Bytes.toBytes("f1"),Bytes.toBytes("sender_network"),Bytes.toBytes(oneMsg.getSender_network()));
                        p.addColumn(Bytes.toBytes("f1"),Bytes.toBytes("sender_gps"),Bytes.toBytes(oneMsg.getSender_gps()));
                        p.addColumn(Bytes.toBytes("f1"),Bytes.toBytes("receiver_nickyname"),Bytes.toBytes(oneMsg.getReceiver_nickyname()));
                        p.addColumn(Bytes.toBytes("f1"),Bytes.toBytes("receiver_ip"),Bytes.toBytes(oneMsg.getReceiver_ip()));
                        p.addColumn(Bytes.toBytes("f1"),Bytes.toBytes("receiver_account"),Bytes.toBytes(oneMsg.getReceiver_account()));
                        p.addColumn(Bytes.toBytes("f1"),Bytes.toBytes("receiver_os"),Bytes.toBytes(oneMsg.getReceiver_os()));
                        p.addColumn(Bytes.toBytes("f1"),Bytes.toBytes("receiver_phone_type"),Bytes.toBytes(oneMsg.getReceiver_phone_type()));
                        p.addColumn(Bytes.toBytes("f1"),Bytes.toBytes("receiver_network"),Bytes.toBytes(oneMsg.getReceiver_network()));
                        p.addColumn(Bytes.toBytes("f1"),Bytes.toBytes("receiver_gps"),Bytes.toBytes(oneMsg.getReceiver_gps()));
                        p.addColumn(Bytes.toBytes("f1"),Bytes.toBytes("receiver_sex"),Bytes.toBytes(oneMsg.getReceiver_sex()));
                        p.addColumn(Bytes.toBytes("f1"),Bytes.toBytes("msg_type"),Bytes.toBytes(oneMsg.getMsg_type()));
                        p.addColumn(Bytes.toBytes("f1"),Bytes.toBytes("distance"),Bytes.toBytes(oneMsg.getDistance()));
                        p.addColumn(Bytes.toBytes("f1"),Bytes.toBytes("message"),Bytes.toBytes(oneMsg.getMessage()));
                        mutator.mutate(p);
                        mutator.flush();
                        // do work... maybe you want to call mutator.flush() after many edits to ensure any of
                        // this worker's edits are sent before exiting the Callable
                        return null;
                    }
                }));
                i++;
            }

            //
            // step 3: clean up the worker pool, shut down.
            //
            for (Future<Void> f : futures) {
                f.get(5, TimeUnit.MINUTES);
            }
            workerPool.shutdown();
        } catch (IOException e) {
            // exception while creating/destroying Connection or BufferedMutator
            LOG.info("exception while creating/destroying Connection or BufferedMutator", e);
        } // BufferedMutator.close() ensures all work is flushed. Could be the custom listener is
        // invoked from here.
        return 0;
    }

    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        ToolRunner.run(new BufferedMutatorExample(), args);
        long end = System.currentTimeMillis();
        System.out.println("耗时：" + (end - start));
    }
}
